import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { User, InterestTag, Match, ChatMessage, Notification } from '../types/api';

interface AuthState {
  user: User | null;
  token: string | null;
  isAuthenticated: boolean;
  login: (user: User, token: string) => void;
  logout: () => void;
  updateUser: (user: Partial<User>) => void;
}

interface AppState {
  currentPage: string;
  isLoading: boolean;
  setCurrentPage: (page: string) => void;
  setLoading: (loading: boolean) => void;
}

interface InterestState {
  selectedTags: InterestTag[];
  availableTags: InterestTag[];
  setSelectedTags: (tags: InterestTag[]) => void;
  setAvailableTags: (tags: InterestTag[]) => void;
  addTag: (tag: InterestTag) => void;
  removeTag: (tagId: number) => void;
}

interface MatchState {
  matches: Match[];
  currentMatch: Match | null;
  setMatches: (matches: Match[]) => void;
  setCurrentMatch: (match: Match | null) => void;
  addMatch: (match: Match) => void;
  updateMatch: (matchId: number, updates: Partial<Match>) => void;
}

interface ChatState {
  messages: Record<number, ChatMessage[]>; // matchId -> messages
  unreadCounts: Record<number, number>; // matchId -> count
  setMessages: (matchId: number, messages: ChatMessage[]) => void;
  addMessage: (matchId: number, message: ChatMessage) => void;
  setUnreadCount: (matchId: number, count: number) => void;
  markAsRead: (matchId: number) => void;
}

interface NotificationState {
  notifications: Notification[];
  unreadCount: number;
  setNotifications: (notifications: Notification[]) => void;
  addNotification: (notification: Notification) => void;
  markAsRead: (notificationId: number) => void;
  setUnreadCount: (count: number) => void;
}

// Auth Store
export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      login: (user, token) => set({ user, token, isAuthenticated: true }),
      logout: () => set({ user: null, token: null, isAuthenticated: false }),
      updateUser: (userData) => set((state) => ({
        user: state.user ? { ...state.user, ...userData } : null
      })),
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({ user: state.user, token: state.token, isAuthenticated: state.isAuthenticated }),
    }
  )
);

// App Store
export const useAppStore = create<AppState>((set) => ({
  currentPage: 'home',
  isLoading: false,
  setCurrentPage: (page) => set({ currentPage: page }),
  setLoading: (loading) => set({ isLoading: loading }),
}));

// Interest Store
export const useInterestStore = create<InterestState>((set) => ({
  selectedTags: [],
  availableTags: [],
  setSelectedTags: (tags) => set({ selectedTags: tags }),
  setAvailableTags: (tags) => set({ availableTags: tags }),
  addTag: (tag) => set((state) => ({
    selectedTags: [...state.selectedTags, tag]
  })),
  removeTag: (tagId) => set((state) => ({
    selectedTags: state.selectedTags.filter(tag => tag.tag_id !== tagId)
  })),
}));

// Match Store
export const useMatchStore = create<MatchState>((set) => ({
  matches: [],
  currentMatch: null,
  setMatches: (matches) => set({ matches }),
  setCurrentMatch: (match) => set({ currentMatch: match }),
  addMatch: (match) => set((state) => ({
    matches: [match, ...state.matches]
  })),
  updateMatch: (matchId, updates) => set((state) => ({
    matches: state.matches.map(match =>
      match.match_id === matchId ? { ...match, ...updates } : match
    )
  })),
}));

// Chat Store
export const useChatStore = create<ChatState>((set) => ({
  messages: {},
  unreadCounts: {},
  setMessages: (matchId, messages) => set((state) => ({
    messages: { ...state.messages, [matchId]: messages }
  })),
  addMessage: (matchId, message) => set((state) => ({
    messages: {
      ...state.messages,
      [matchId]: [...(state.messages[matchId] || []), message]
    }
  })),
  setUnreadCount: (matchId, count) => set((state) => ({
    unreadCounts: { ...state.unreadCounts, [matchId]: count }
  })),
  markAsRead: (matchId) => set((state) => ({
    unreadCounts: { ...state.unreadCounts, [matchId]: 0 }
  })),
}));

// Notification Store
export const useNotificationStore = create<NotificationState>((set) => ({
  notifications: [],
  unreadCount: 0,
  setNotifications: (notifications) => set({ notifications }),
  addNotification: (notification) => set((state) => ({
    notifications: [notification, ...state.notifications],
    unreadCount: notification.is_read ? state.unreadCount : state.unreadCount + 1
  })),
  markAsRead: (notificationId) => set((state) => ({
    notifications: state.notifications.map(notif =>
      notif.notification_id === notificationId ? { ...notif, is_read: true } : notif
    ),
    unreadCount: Math.max(0, state.unreadCount - 1)
  })),
  setUnreadCount: (count) => set({ unreadCount: count }),
}));
